<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会议活动座次图排版打印工具（V1.0）</title>
    <style>
        /* 样式保持不变，与原始代码相同 */
        :root {
            --primary-color: #2c3e50;
            --secondary-color: #3498db;
            --accent-color: #e74c3c;
            --light-color: #ecf0f1;
            --seat-width: 80px;
            --seat-height: 60px;
            --gap: 10px;
            --aisle-color: #f0f0f0;
            --stage-row-gap: 15px;
            --audience-row-gap: 15px;
            --stage-audience-gap: 40px;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f5f5f5;
            padding: 20px;
            width: 100%;
            overflow-x: auto;
        }
        
        .container {
            width: 100%;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
            padding: 20px;
            display: grid;
            grid-template-columns: 280px 1fr;
            gap: 20px;
            min-width: 1000px;
        }
        
        header {
            grid-column: 1 / -1;
            text-align: center;
            margin-bottom: 20px;
        }
        
        h1 {
            color: var(--primary-color);
            margin-bottom: 10px;
        }
        
		.description-row {
			display: inline-flex;
			align-items: center;
			justify-content: center;
			gap: 10px;
			font-size: 14px;
			color: #666;
			margin-bottom: 14px;
		}

		.description-row button {
			padding: 4px 10px;
			background: #2c3e50;
			color: white;
			border: none;
			border-radius: 4px;
			cursor: pointer;
			font-size: 14px;
		}
        
        .control-panel {
            background: var(--light-color);
            padding: 15px;
            border-radius: 6px;
            height: fit-content;
            max-height: 80vh;
            overflow-y: auto;
            position: sticky;
            top: 20px;
        }
        
        /* 新增：顶部工具栏样式 */
        .top-toolbar {
            position: sticky;
            top: 0;
            z-index: 100;
            background: var(--light-color);
            padding: 10px 0;
            margin: -15px -15px 15px -15px;
            border-bottom: 1px solid #ddd;
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
            justify-content: center;
        }
        
        .top-toolbar button {
            flex: 1;
            min-width: 60px;
            padding: 6px;
            font-size: 12px;
            margin-bottom: 0;
        }
        
        .control-group {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #ddd;
        }
        
        .control-group:last-child {
            border-bottom: none;
        }
        
        .control-group h3 {
            margin-bottom: 10px;
            color: var(--primary-color);
            font-size: 16px;
        }
        
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        input, select, button, textarea {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        button {
            background: var(--secondary-color);
            color: white;
            border: none;
            cursor: pointer;
            transition: background 0.3s;
            font-weight: bold;
        }
        
        button:hover {
            background: #2980b9;
        }
        
        .btn-danger {
            background: var(--accent-color);
        }
        
        .btn-danger:hover {
            background: #c0392b;
        }
        
        .btn-disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        
        .btn-disabled:hover {
            background: #ccc;
        }
        
        .color-preview {
            display: inline-block;
            width: 20px;
            height: 20px;
            border-radius: 4px;
            margin-right: 5px;
            vertical-align: middle;
        }
        
        .seating-area {
            min-height: 600px;
            border: 1px dashed #ccc;
            padding: 20px;
            border-radius: 6px;
            background: #f9f9f9;
            overflow: auto;
            width: 100%;
        }
        
        .conference-title {
            text-align: center;
            margin-bottom: 30px;
            padding: 10px;
            background: #eee;
            border-radius: 4px;
            cursor: pointer;
            font-size: 24px;
        }
        
        .conference-title:hover {
            background: #ddd;
        }
        
        .stage-container {
            display: flex;
            flex-direction: column-reverse; /* 主席台从下往上排列 */
            align-items: flex-start;
            gap: var(--stage-row-gap);
            margin-bottom: var(--stage-audience-gap);
            width: 100%;
            position: relative;
        }
        
        .stage-row {
            display: flex;
            gap: var(--gap);
            position: relative;
            width: 100%;
            padding-left: 40px; /* 为行号预留空间 */
        }
        
        .stage-row-label {
            position: absolute;
            left: 0;
            top: 0;
            width: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            height: var(--seat-height);
            line-height: var(--seat-height);
            flex-shrink: 0;
        }
        
        .stage-row-content {
            display: flex;
            gap: var(--gap);
            flex-wrap: wrap;
            position: relative;
            min-height: var(--seat-height);
            width: 100%;
        }
        
        .audience {
            display: flex;
            flex-direction: column;
            align-items: flex-start;
            gap: var(--audience-row-gap);
            width: 100%;
        }
        
        .row {
            display: flex;
            gap: var(--gap);
            margin-bottom: 0;
            align-items: flex-start;
            width: 100%;
            position: relative;
            padding-left: 40px; /* 为行号预留空间 */
        }
        
        .row-label {
            position: absolute;
            left: 0;
            top: 0;
            width: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            height: var(--seat-height);
            line-height: var(--seat-height);
            flex-shrink: 0;
        }
        
        .row-content {
            display: flex;
            gap: var(--gap);
            flex-wrap: wrap;
            position: relative;
            min-height: var(--seat-height);
            width: 100%;
        }
        
        .row-content.custom-layout {
            justify-content: flex-start !important;
            margin: 0 !important;
        }
        
        .seat {
            width: var(--seat-width);
            min-height: var(--seat-height);
            border: 1px solid #999;
            border-radius: 6px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s;
            position: relative;
            overflow: hidden;
            text-align: center;
            padding: 5px;
            word-break: break-word;
            flex-shrink: 0;
        }
        
        .seat:hover {
            transform: scale(1.05);
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
        }
        
        .seat.selected {
            border: 2px solid var(--accent-color);
        }
        
        .seat.dragging {
            opacity: 0.7;
            z-index: 100;
        }
        
        .empty-space {
            width: var(--seat-width);
            height: var(--seat-height);
            flex-shrink: 0;
            visibility: hidden;
        }
        
        .seat-number {
            font-weight: bold;
            margin-bottom: 3px;
        }
        
        .seat-name {
            line-height: 1.2;
        }
        
        .aisle {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: var(--aisle-color);
            font-weight: bold;
            color: #666;
            flex-shrink: 0;
        }
        
        .horizontal-aisle {
            width: 100%;
            height: 40px;
            margin: 10px 0;
        }
        
        .vertical-aisle {
            width: 40px;
            height: var(--seat-height);
            margin: 0 10px;
        }
        
        .legend {
            margin-top: 30px;
            display: flex;
            flex-wrap: wrap;
            gap: 15px;
            justify-content: center;
            width: 100%;
        }
        
        .legend-item {
            display: flex;
            align-items: center;
            margin-right: 15px;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }
        
        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 400px;
            max-width: 90%;
        }
        
        .modal h2 {
            margin-bottom: 15px;
            color: var(--primary-color);
        }
        
        .hidden {
            display: none;
        }
        
        .file-input {
            display: none;
        }
        
        .custom-layout-hint {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            font-weight: bold;
            padding: 10px;
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 4px;
            margin-bottom: 20px;
            display: none;
        }
        
        .toggle-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .toggle-label {
            margin-left: 10px;
            font-weight: normal;
        }
        
        .toggle-switch {
            position: relative;
            display: inline-block;
            width: 50px;
            height: 24px;
        }
        
        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }
        
        .toggle-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: #ccc;
            transition: .4s;
            border-radius: 24px;
        }
        
        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 4px;
            bottom: 4px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }
        
        input:checked + .toggle-slider {
            background-color: var(--secondary-color);
        }
        
        input:checked + .toggle-slider:before {
            transform: translateX(26px);
        }
        
        @media print {
            body, .container {
                margin: 0;
                padding: 0;
                box-shadow: none;
                background: white;
                width: 100%;
                overflow: visible !important;
            }
            
            .control-panel, button, header, .description {
                display: none;
            }
            
            .container {
                grid-template-columns: 1fr;
                width: 100%;
                min-width: auto;
            }
            
            .seating-area {
                border: none;
                padding: 0;
                width: 100%;
                overflow: visible !important;
            }
            
            .seat {
                box-shadow: none;
                border: 1px solid #000;
                color: black !important;
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
            }
            
            /* 修复打印布局问题 */
            .row-content {
                display: flex !important;
                flex-wrap: wrap !important;
                position: relative !important;
                gap: var(--gap) !important;
            }
            
            .row-content.custom-layout .seat {
                position: relative !important;
                left: auto !important;
                top: auto !important;
            }
            
            .aisle {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                background-color: var(--aisle-color) !important;
            }
            
            .legend-item .color-preview {
                -webkit-print-color-adjust: exact !important;
                print-color-adjust: exact !important;
                border: 1px solid #000;
            }
            
            /* 确保打印时所有内容都显示 */
            .row {
                page-break-inside: avoid;
            }
            
            .stage-container, .audience, .legend {
                page-break-inside: avoid;
            }
            
            .custom-layout-hint {
                display: none !important;
            }
            
            /* 打印时确保行号区域不影响布局 */
            .stage-row, .row {
                padding-left: 0;
            }
            
            .stage-row-label, .row-label {
                position: static;
                width: 30px;
                margin-right: 10px;
            }
            
            /* 隐藏顶部工具栏 */
            .top-toolbar {
                display: none;
            }
        }
        
        @media (max-width: 1200px) {
            .container {
                grid-template-columns: 1fr;
            }
            
            .control-panel {
                margin-bottom: 20px;
                max-height: none;
                position: static;
            }
            
            .top-toolbar {
                position: static;
            }
        }
		
		#instructionModal .modal-content {
			max-width: 80vw;
			width: 100%;
			padding: 30px;
			font-size: 16px;
			line-height: 1.8;
			border-radius: 12px;
			box-shadow: 0 8px 30px rgba(0, 0, 0, 0.2);
			background: #fafafa;
			color: #333;
		}
    </style>
</head>
<body>
    <div class="container">
        <header>
            <h1>会议活动座次图排版打印工具</h1>
			<div style="display:inline-flex; align-items:center; justify-content:center; gap:10px; font-size:14px; color:#666; white-space:nowrap;">
				Developed by Hyond & DeepSeek.
				<button id="instructionBtn" style="padding:4px 10px; background:#2c3e50; color:white; border:none; border-radius:4px; cursor:pointer;">操作说明</button>
			</div>
        </header>
        
        <div class="control-panel">
            <!-- 新增：顶部工具栏 -->
            <div class="top-toolbar">
                <button id="resetAllBtn" class="btn-danger" title="重置所有数据">重置</button>
                <button id="applyAllBtn" title="应用所有设置">应用</button>
                <button id="undoBtn" class="btn-disabled" title="撤销上一步操作">撤销</button>
                <button id="redoBtn" class="btn-disabled" title="重做已撤销的操作">重做</button>
            </div>
            
            <div class="control-group">
                <h3>会议标题设置</h3>
                <input type="text" id="conferenceTitle" value="会议活动名称" placeholder="输入会议标题">
                <input type="number" id="titleFontSize" value="24" min="10" max="50" placeholder="标题字体大小">
            </div>
            
            <div class="control-group">
                <h3>主席台设置</h3>
                <label for="stageRows">排数</label>
                <input type="number" id="stageRows" value="1" min="1" max="5">
                
                <label for="stageSeatsPerRow">每排座位数</label>
                <input type="number" id="stageSeatsPerRow" value="3" min="1" max="10">
                
                <label for="stageSeatWidth">座椅宽度(px)</label>
                <input type="number" id="stageSeatWidth" value="100" min="50" max="150">
                
                <label for="stageSeatHeight">座椅高度(px)</label>
                <input type="number" id="stageSeatHeight" value="70" min="40" max="120">
                
                <label for="stageAlignment">排列方式</label>
                <select id="stageAlignment">
                    <option value="left">居左</option>
                    <option value="center" selected>居中</option>
                    <option value="right">居右</option>
                </select>
            </div>
            
            <div class="control-group">
                <h3>观众席设置</h3>
                <label for="rows">排数</label>
                <input type="number" id="rows" value="5" min="1" max="20">
                
                <label for="seatsPerRow">每排座位数</label>
                <input type="number" id="seatsPerRow" value="6" min="1" max="15">
                
                <label for="seatWidth">座椅宽度(px)</label>
                <input type="number" id="seatWidth" value="80" min="50" max="150">
                
                <label for="seatHeight">座椅高度(px)</label>
                <input type="number" id="seatHeight" value="60" min="40" max="120">
                
                <label for="rowAlignment">排列方式</label>
                <select id="rowAlignment">
                    <option value="left">居左</option>
                    <option value="center" selected>居中</option>
                    <option value="right">居右</option>
                    <option value="custom">自定义</option>
                </select>
                <div class="custom-layout-hint" id="customLayoutHint">
                    自定义排列模式：座椅位置将保持不变，不会自动对齐
                </div>
            </div>
            
            <div class="control-group">
                <h3>排序设置</h3>
                <label for="sortingMethod">排序方式</label>
                <select id="sortingMethod">
                    <option value="leftToRight" selected>从左向右排序（默认）</option>
                    <option value="rightToLeft">从右向左排序</option>
                    <option value="centerToSidesLeftFirst">中间向两侧排序（左为尊）</option>
                    <option value="centerToSidesRightFirst">中间向两侧排序（右为尊）</option>
                </select>
                <button id="applySorting">应用排序</button>
                <p style="font-size: 12px; color: #666; margin-top: 5px;">
                    注意：排序只影响座牌名称顺序，不改变座椅编号。主席台排序方式与观众席相反。
                </p>
            </div>
            
            <div class="control-group">
                <h3>间距设置</h3>
                <label for="stageRowGap">主席台行间距(px)</label>
                <input type="number" id="stageRowGap" value="15" min="5" max="50">
                
                <label for="audienceRowGap">观众席行间距(px)</label>
                <input type="number" id="audienceRowGap" value="15" min="5" max="50">
                
                <label for="stageAudienceGap">主席台与观众席间距(px)</label>
                <input type="number" id="stageAudienceGap" value="40" min="20" max="100">
            </div>
            
            <div class="control-group">
                <h3>过道设置</h3>
                <label for="horizontalAisles">横向过道（排号，用逗号分隔）</label>
                <input type="text" id="horizontalAisles" placeholder="例如: 2,4">
                
                <label for="verticalAisles">纵向过道（列号，用逗号分隔）</label>
                <input type="text" id="verticalAisles" placeholder="例如: 2,5">
                
                <label for="aisleFontSize">过道字体大小</label>
                <input type="number" id="aisleFontSize" value="14" min="8" max="24">
                
                <label for="aisleColor">过道背景颜色</label>
                <input type="color" id="aisleColor" value="#f0f0f0">
            </div>
            
            <div class="control-group">
                <h3>座位显示设置</h3>
                <select id="seatDisplay">
                    <option value="both" selected>显示编号和名称</option>
                    <option value="number">仅显示编号</option>
                    <option value="name">仅显示名称</option>
                    <option value="none">都不显示</option>
                </select>
                
                <label for="seatFontSize">字体大小</label>
                <input type="number" id="seatFontSize" value="12" min="8" max="20">
                
                <div class="toggle-container">
                    <label class="toggle-switch">
                        <input type="checkbox" id="showSeatTypes" checked>
                        <span class="toggle-slider"></span>
                    </label>
                    <span class="toggle-label">显示座位类别</span>
                </div>
            </div>
            
            <div class="control-group">
                <h3>座位类别设置</h3>
                <div id="seatTypes">
                    <div class="seat-type">
                        <input type="color" value="#3498db">
                        <input type="text" value="普通代表" placeholder="类别名称">
                    </div>
                    <div class="seat-type">
                        <input type="color" value="#e74c3c">
                        <input type="text" value="VIP代表" placeholder="类别名称">
                    </div>
                    <div class="seat-type">
                        <input type="color" value="#2ecc71">
                        <input type="text" value="工作人员" placeholder="类别名称">
                    </div>
                </div>
                <button id="addSeatType">添加类别</button>
            </div>
            
            <div class="control-group">
                <h3>数据操作</h3>
                <input type="file" id="csvFile" class="file-input" accept=".csv">
                <button id="importBtn">导入CSV</button>
                <button id="exportBtn">导出CSV</button>
                <button id="printBtn">打印座次图</button>
                <button id="resetBtn" class="btn-danger">重置所有数据</button>
            </div>
            
            <div class="control-group">
                <button id="applySettings">应用所有设置</button>
            </div>
        </div>
        
        <div class="seating-area">
            <div class="conference-title" id="conferenceTitleDisplay">
                会议活动名称
            </div>
            
            <div class="stage-container" id="stageContainer">
                <!-- 主席台座位将通过JS动态生成 -->
            </div>
            
            <div class="audience" id="audienceContainer">
                <!-- 观众席座位将通过JS动态生成 -->
            </div>
            
            <div class="legend" id="legendContainer">
                <!-- 图例将通过JS动态生成 -->
            </div>
        </div>
    </div>

    <!-- 编辑座位的模态框 -->
    <div class="modal" id="editSeatModal">
        <div class="modal-content">
            <h2>编辑座位信息</h2>
            <label for="editSeatNumber">座位编号</label>
            <input type="text" id="editSeatNumber">
            
            <label for="editSeatName">座牌名称</label>
            <textarea id="editSeatName" rows="3"></textarea>
            
            <label for="editSeatType">座位类别</label>
            <select id="editSeatType">
                <option value="0">普通代表</option>
                <option value="1">VIP代表</option>
                <option value="2">工作人员</option>
            </select>
            
            <div style="margin-top: 20px; display: flex; justify-content: space-between;">
                <button id="saveSeatBtn">保存</button>
                <button id="cancelEditBtn" class="btn-danger">取消</button>
                <button id="deleteSeatBtn" class="btn-danger">删除座位</button>
            </div>
        </div>
    </div>
	
	<div class="modal" id="instructionModal">
		<div class="modal-content">
			<h2 style="color: #2c3e50; margin-bottom: 20px; text-align: center;">📘 会议活动座次图排版打印工具 - 操作说明</h2>

			<div style="max-height: 70vh; overflow-y: auto; padding-right: 10px;">
				<h3 style="color: #3498db; border-bottom: 2px solid #3498db; padding-bottom: 5px;">一、基本功能介绍</h3>
				<p>本工具是一款便捷的会议、活动座次图排版与打印工具，支持以下功能：</p>
				<ul style="list-style-type: none; padding-left: 20px;">
					<li style="margin-bottom: 8px;">✅ <strong>主席台与观众席分区设置</strong> - 可分别设置不同区域的座位布局</li>
					<li style="margin-bottom: 8px;">✅ <strong>座位信息自定义</strong> - 支持编号、名称、类别设置</li>
					<li style="margin-bottom: 8px;">✅ <strong>多种排序方式</strong> - 左→右、右→左、中间→两侧等多种排序规则</li>
					<li style="margin-bottom: 8px;">✅ <strong>数据导入/导出</strong> - 支持CSV格式数据交换（UTF-8编码）</li>
					<li style="margin-bottom: 8px;">✅ <strong>打印与PDF导出</strong> - 一键生成专业座次图</li>
					<li style="margin-bottom: 8px;">✅ <strong>撤销/重做功能</strong> - 支持操作历史记录，最多保存50步</li>
					<li style="margin-bottom: 8px;">✅ <strong>自定义布局</strong> - 可拖拽调整座位位置</li>
					<li style="margin-bottom: 8px;">✅ <strong>过道设置</strong> - 支持横向和纵向过道添加</li>
					<li style="margin-bottom: 8px;">✅ <strong>座位类别管理</strong> - 使用不同颜色区分不同类型的参会人员</li>
				</ul>

				<h3 style="color: #3498db; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-top: 25px;">二、详细操作步骤</h3>
				<ol>
					<li style="margin-bottom: 15px;">
						<strong>设置会议标题</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在左侧控制面板的"会议标题设置"区域输入会议名称</li>
							<li>调整标题字体大小（默认24px，范围10-50px）</li>
							<li>标题可编辑，会实时显示在座次图顶部</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>设置主席台</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在"主席台设置"区域设置排数</li>
							<li>设置每排座位数</li>
							<li>调整座椅宽度和高度（px为单位）</li>
							<li>选择排列方式：居左、居中或居右</li>
							<li>主席台座位默认从下往上排列（第1排在最下方）</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>设置观众席</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在"观众席设置"区域设置排数</li>
							<li>设置每排座位数</li>
							<li>调整座椅宽度和高度（px为单位）</li>
							<li>选择排列方式：居左、居中、居右或自定义</li>
							<li>观众席座位默认从上往下排列（第1排在最上方）</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>添加过道</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在"过道设置"区域添加横向过道：输入排号（用逗号分隔，如"4,7"表示在第4排和第7排前添加过道）</li>
							<li>添加纵向过道：输入列号（用逗号分隔，如"3,6"表示在第3列和第6列前添加过道）</li>
							<li>可调整过道字体大小和背景颜色</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>设置座位类别</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在"座位类别设置"区域管理不同类别</li>
							<li>点击颜色选择器可更改类别颜色</li>
							<li>在文本框中输入类别名称（如"普通代表"、"VIP代表"等）</li>
							<li>点击"添加类别"按钮可增加新类别</li>
							<li>可通过"显示座位类别"开关控制是否显示颜色区分</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>编辑座位信息</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>点击任意座位可打开编辑对话框</li>
							<li>可修改座位编号、座牌名称和类别</li>
							<li>点击"删除座位"可将该位置设为空位</li>
							<li>可直接拖拽座位对换调整位置</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>排序设置</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>在"排序设置"区域选择排序方式</li>
							<li>点击"应用排序"按钮使设置生效</li>
							<li>注意：主席台排序方式与观众席相反（两者相对，所以排序关系相反）</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>数据导入/导出</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>点击"导入CSV"可导入预先准备的座位数据</li>
							<li>CSV文件格式：位置(0=主席台/1=观众席),行号,列号,座椅编号,座牌名称,类别</li>
							<li>点击"导出CSV"可将当前数据导出为CSV文件</li>
							<li>所有数据会自动保存在浏览器本地，刷新页面不会丢失</li>
						</ul>
					</li>
					
					<li style="margin-bottom: 15px;">
						<strong>打印座次图</strong>
						<ul style="list-style-type: circle; margin-top: 5px; margin-bottom: 10px;">
							<li>点击"打印座次图"按钮可调起打印对话框</li>
							<li>打印前建议使用浏览器的打印预览功能检查布局，可以通过选择打印纸张（A4、A3等）、调整缩放比例让打印界面更加美观合理</li>
							<li>可选择"另存为PDF"将座次图保存为PDF文件</li>
						</ul>
					</li>
				</ol>

				<h3 style="color: #3498db; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-top: 25px;">三、顶部工具栏功能</h3>
				<ul style="list-style-type: none; padding-left: 20px;">
					<li style="margin-bottom: 8px;">🔄 <strong>重置</strong> - 清除所有数据，恢复默认设置</li>
					<li style="margin-bottom: 8px;">✅ <strong>应用</strong> - 应用所有设置更改</li>
					<li style="margin-bottom: 8px;">↩️ <strong>撤销</strong> - 撤销上一步操作（最多50步历史记录）</li>
					<li style="margin-bottom: 8px;">↪️ <strong>重做</strong> - 重做已撤销的操作</li>
				</ul>

				<h3 style="color: #3498db; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-top: 25px;">四、注意事项</h3>
				<div style="background-color: #fff3cd; border-left: 4px solid #ffeaa7; padding: 10px 15px; margin: 15px 0;">
					<ul style="list-style-type: none; padding-left: 10px;">
						<li style="margin-bottom: 8px;">⚠️ CSV文件必须使用 <strong>UTF-8 编码</strong>，否则中文会显示乱码</li>
						<li style="margin-bottom: 8px;">⚠️ 如出现乱码，请用记事本打开CSV文件 → 另存为 → 编码选择"UTF-8"</li>
						<li style="margin-bottom: 8px;">⚠️ 自定义排列模式下，座椅位置将保存在浏览器本地存储中</li>
						<li style="margin-bottom: 8px;">⚠️ 清除浏览器缓存会导致自定义布局丢失，建议定期导出CSV备份数据</li>
						<li style="margin-bottom: 8px;">⚠️ 打印前请使用浏览器"打印预览"功能检查布局，确保所有内容正常显示</li>
						<li style="margin-bottom: 8px;">⚠️ 主席台排序规则与观众席相反</li>
					</ul>
				</div>

				<h3 style="color: #3498db; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-top: 25px;">五、排序规则说明</h3>
				<p>不同排序方式对座位名称的分配规则（以4个座位为例）：</p>
				<table border="1" cellpadding="8" style="width: 100%; border-collapse: collapse; margin-top: 10px; margin-bottom: 20px;">
					<thead>
						<tr style="background-color: #2c3e50; color: white;">
							<th style="text-align: center;">排序方式</th>
							<th style="text-align: center;">说明</th>
							<th style="text-align: center;">座位名称分配顺序</th>
						</tr>
					</thead>
					<tbody>
						<tr>
							<td style="text-align: center; font-weight: bold;">从左向右</td>
							<td>从左到右依次分配名称</td>
							<td style="text-align: center;">1, 2, 3, 4, 5</td>
						</tr>
						<tr style="background-color: #f9f9f9;">
							<td style="text-align: center; font-weight: bold;">从右向左</td>
							<td>从右到左依次分配名称</td>
							<td style="text-align: center;">5, 4, 3, 2, 1</td>
						</tr>
						<tr>
							<td style="text-align: center; font-weight: bold;">中间向两侧（左为尊）</td>
							<td>中间位置最重要，优先左侧</td>
							<td style="text-align: center;">4, 2, 1, 3, 5</td>
						</tr>
						<tr style="background-color: #f9f9f9;">
							<td style="text-align: center; font-weight: bold;">中间向两侧（右为尊）</td>
							<td>中间位置最重要，优先右侧</td>
							<td style="text-align: center;">5, 3, 1, 2, 4</td>
						</tr>
					</tbody>
				</table>
			</div>

			<div style="text-align: center; margin-top: 25px;">
				<button id="closeInstructionBtn" style="padding: 10px 30px; background: #2c3e50; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px;">关闭说明</button>
			</div>
		</div>
	</div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化变量
            let currentSeat = null;
            let dragging = false;
            let dragSource = null;
            let seatData = {};
            let isDataImported = false;
            let isCustomLayout = false;
            
            // 新增：历史记录管理
            let historyStack = [];
            let currentHistoryIndex = -1;
            const MAX_HISTORY = 50;
            
            // DOM元素引用
            const conferenceTitleDisplay = document.getElementById('conferenceTitleDisplay');
            const stageContainer = document.getElementById('stageContainer');
            const audienceContainer = document.getElementById('audienceContainer');
            const legendContainer = document.getElementById('legendContainer');
            const editSeatModal = document.getElementById('editSeatModal');
            const csvFileInput = document.getElementById('csvFile');
            const customLayoutHint = document.getElementById('customLayoutHint');
            const rowAlignmentSelect = document.getElementById('rowAlignment');
            const showSeatTypesCheckbox = document.getElementById('showSeatTypes');
            
            // 新增：顶部工具栏按钮
            const resetAllBtn = document.getElementById('resetAllBtn');
            const applyAllBtn = document.getElementById('applyAllBtn');
            const undoBtn = document.getElementById('undoBtn');
            const redoBtn = document.getElementById('redoBtn');
            
            // 初始化座次图
            initializeSeatingChart();
			
			// 获取操作说明按钮和模态框元素
			const instructionBtn = document.getElementById('instructionBtn');
			const instructionModal = document.getElementById('instructionModal');
			const closeInstructionBtn = document.getElementById('closeInstructionBtn');
			
			// 添加操作说明按钮点击事件
			instructionBtn.addEventListener('click', function() {
				instructionModal.style.display = 'flex';
			});
			
			// 添加关闭按钮点击事件
			closeInstructionBtn.addEventListener('click', function() {
				instructionModal.style.display = 'none';
			});
			
			// 点击模态框外部也可关闭
			instructionModal.addEventListener('click', function(e) {
				if (e.target === instructionModal) {
					instructionModal.style.display = 'none';
				}
			});
            
            // 绑定事件
            document.getElementById('applySettings').addEventListener('click', applySettings);
            document.getElementById('conferenceTitle').addEventListener('input', updateConferenceTitle);
            document.getElementById('titleFontSize').addEventListener('input', updateConferenceTitle);
            document.getElementById('seatDisplay').addEventListener('change', updateSeatDisplay);
            document.getElementById('seatFontSize').addEventListener('input', updateSeatFontSize);
            document.getElementById('seatWidth').addEventListener('input', updateSeatSize);
            document.getElementById('seatHeight').addEventListener('input', updateSeatSize);
            document.getElementById('stageSeatWidth').addEventListener('input', updateStageSeatSize);
            document.getElementById('stageSeatHeight').addEventListener('input', updateStageSeatSize);
            document.getElementById('stageRowGap').addEventListener('input', updateGaps);
            document.getElementById('audienceRowGap').addEventListener('input', updateGaps);
            document.getElementById('stageAudienceGap').addEventListener('input', updateGaps);
            document.getElementById('aisleColor').addEventListener('input', updateAisleColor);
            document.getElementById('addSeatType').addEventListener('click', addSeatType);
            document.getElementById('printBtn').addEventListener('click', printSeatingChart);
            document.getElementById('resetBtn').addEventListener('click', resetAllData);
            document.getElementById('importBtn').addEventListener('click', () => csvFileInput.click());
            document.getElementById('exportBtn').addEventListener('click', exportCSV);
            document.getElementById('saveSeatBtn').addEventListener('click', saveSeatEdit);
            document.getElementById('cancelEditBtn').addEventListener('click', closeEditModal);
            document.getElementById('deleteSeatBtn').addEventListener('click', deleteSeat);
            csvFileInput.addEventListener('change', importCSV);
            rowAlignmentSelect.addEventListener('change', toggleCustomLayoutHint);
            showSeatTypesCheckbox.addEventListener('change', updateSeatTypeVisibility);
            document.getElementById('applySorting').addEventListener('click', applySorting);
            
            // 新增：顶部工具栏按钮事件
            resetAllBtn.addEventListener('click', resetAllData);
            applyAllBtn.addEventListener('click', applySettings);
            undoBtn.addEventListener('click', undoAction);
            redoBtn.addEventListener('click', redoAction);
            
            // 初始化座次图函数
            function initializeSeatingChart() {
                generateStageSeats();
                generateAudienceSeats();
                updateLegend();
                updateConferenceTitle();
                updateSeatSize();
                updateStageSeatSize();
                updateGaps();
                updateAisleColor();
                toggleCustomLayoutHint();
                updateSeatTypeVisibility();
                
                // 初始化座位数据
                saveSeatData();
                
                // 新增：保存初始状态到历史记录
                saveStateToHistory();
            }
            
            // 新增：保存状态到历史记录
            function saveStateToHistory() {
                // 如果当前不在历史记录的最新位置，删除后面的记录
                if (currentHistoryIndex < historyStack.length - 1) {
                    historyStack = historyStack.slice(0, currentHistoryIndex + 1);
                }
                
                // 保存当前状态
                const state = {
                    seatData: getAllSeatData(),
                    settings: getAllSettings()
                };
                
                historyStack.push(JSON.stringify(state));
                
                // 限制历史记录数量
                if (historyStack.length > MAX_HISTORY) {
                    historyStack.shift();
                }
                
                currentHistoryIndex = historyStack.length - 1;
                
                // 更新撤销/重做按钮状态
                updateUndoRedoButtons();
            }
            
            // 新增：获取所有设置
            function getAllSettings() {
                return {
                    conferenceTitle: document.getElementById('conferenceTitle').value,
                    titleFontSize: document.getElementById('titleFontSize').value,
                    stageRows: document.getElementById('stageRows').value,
                    stageSeatsPerRow: document.getElementById('stageSeatsPerRow').value,
                    stageSeatWidth: document.getElementById('stageSeatWidth').value,
                    stageSeatHeight: document.getElementById('stageSeatHeight').value,
                    stageAlignment: document.getElementById('stageAlignment').value,
                    rows: document.getElementById('rows').value,
                    seatsPerRow: document.getElementById('seatsPerRow').value,
                    seatWidth: document.getElementById('seatWidth').value,
                    seatHeight: document.getElementById('seatHeight').value,
                    rowAlignment: document.getElementById('rowAlignment').value,
                    stageRowGap: document.getElementById('stageRowGap').value,
                    audienceRowGap: document.getElementById('audienceRowGap').value,
                    stageAudienceGap: document.getElementById('stageAudienceGap').value,
                    horizontalAisles: document.getElementById('horizontalAisles').value,
                    verticalAisles: document.getElementById('verticalAisles').value,
                    aisleFontSize: document.getElementById('aisleFontSize').value,
                    aisleColor: document.getElementById('aisleColor').value,
                    seatDisplay: document.getElementById('seatDisplay').value,
                    seatFontSize: document.getElementById('seatFontSize').value,
                    showSeatTypes: document.getElementById('showSeatTypes').checked,
                    sortingMethod: document.getElementById('sortingMethod').value
                };
            }
            
            // 新增：应用所有设置
            function applyAllSettings(settings) {
                document.getElementById('conferenceTitle').value = settings.conferenceTitle;
                document.getElementById('titleFontSize').value = settings.titleFontSize;
                document.getElementById('stageRows').value = settings.stageRows;
                document.getElementById('stageSeatsPerRow').value = settings.stageSeatsPerRow;
                document.getElementById('stageSeatWidth').value = settings.stageSeatWidth;
                document.getElementById('stageSeatHeight').value = settings.stageSeatHeight;
                document.getElementById('stageAlignment').value = settings.stageAlignment;
                document.getElementById('rows').value = settings.rows;
                document.getElementById('seatsPerRow').value = settings.seatsPerRow;
                document.getElementById('seatWidth').value = settings.seatWidth;
                document.getElementById('seatHeight').value = settings.seatHeight;
                document.getElementById('rowAlignment').value = settings.rowAlignment;
                document.getElementById('stageRowGap').value = settings.stageRowGap;
                document.getElementById('audienceRowGap').value = settings.audienceRowGap;
                document.getElementById('stageAudienceGap').value = settings.stageAudienceGap;
                document.getElementById('horizontalAisles').value = settings.horizontalAisles;
                document.getElementById('verticalAisles').value = settings.verticalAisles;
                document.getElementById('aisleFontSize').value = settings.aisleFontSize;
                document.getElementById('aisleColor').value = settings.aisleColor;
                document.getElementById('seatDisplay').value = settings.seatDisplay;
                document.getElementById('seatFontSize').value = settings.seatFontSize;
                document.getElementById('showSeatTypes').checked = settings.showSeatTypes;
                document.getElementById('sortingMethod').value = settings.sortingMethod;
            }
            
            // 新增：撤销操作
            function undoAction() {
                if (currentHistoryIndex > 0) {
                    currentHistoryIndex--;
                    restoreStateFromHistory();
                }
            }
            
            // 新增：重做操作
            function redoAction() {
                if (currentHistoryIndex < historyStack.length - 1) {
                    currentHistoryIndex++;
                    restoreStateFromHistory();
                }
            }
            
            // 新增：从历史记录恢复状态
			function restoreStateFromHistory() {
				if (historyStack.length === 0 || currentHistoryIndex < 0) return;
				
				const state = JSON.parse(historyStack[currentHistoryIndex]);
				
				// 应用保存的设置
				applyAllSettings(state.settings);
				
				// 重新生成座位布局
				generateStageSeats();
				generateAudienceSeats();
				
				// 应用保存的座位数据（包括已删除的座位）
				applySeatData(state.seatData);
				
				// 更新UI
				updateLegend();
				updateConferenceTitle();
				updateSeatDisplay();
				updateSeatFontSize();
				updateSeatSize();
				updateStageSeatSize();
				updateGaps();
				updateAisleColor();
				toggleCustomLayoutHint();
				updateSeatTypeVisibility();
				
				// 如果是自定义排列模式，恢复自定义位置
				const alignment = document.getElementById('rowAlignment').value;
				if (alignment === 'custom') {
					const rows = audienceContainer.querySelectorAll('.row-content');
					rows.forEach((rowContent, index) => {
						applyCustomLayout(rowContent, index);
					});
				}
				
				// 更新撤销/重做按钮状态
				updateUndoRedoButtons();
			}
            
            // 新增：更新撤销/重做按钮状态
            function updateUndoRedoButtons() {
                // 更新撤销按钮状态
                if (currentHistoryIndex > 0) {
                    undoBtn.classList.remove('btn-disabled');
                    undoBtn.disabled = false;
                } else {
                    undoBtn.classList.add('btn-disabled');
                    undoBtn.disabled = true;
                }
                
                // 更新重做按钮状态
                if (currentHistoryIndex < historyStack.length - 1) {
                    redoBtn.classList.remove('btn-disabled');
                    redoBtn.disabled = false;
                } else {
                    redoBtn.classList.add('btn-disabled');
                    redoBtn.disabled = true;
                }
            }
            
            // 切换自定义布局提示
            function toggleCustomLayoutHint() {
                const alignment = document.getElementById('rowAlignment').value;
                if (alignment === 'custom') {
                    customLayoutHint.style.display = 'block';
                    isCustomLayout = true;
                } else {
                    customLayoutHint.style.display = 'none';
                    isCustomLayout = false;
                }
            }
            
            // 更新座位类型显示状态
            function updateSeatTypeVisibility() {
                const showTypes = showSeatTypesCheckbox.checked;
                const seats = document.querySelectorAll('.seat');
                const legend = document.getElementById('legendContainer');
                
                // 显示或隐藏图例
                legend.style.display = showTypes ? 'flex' : 'none';
                
                // 更新所有座位颜色
                seats.forEach(seat => {
                    if (showTypes) {
                        seat.style.backgroundColor = getSeatTypeColor(seat.dataset.type);
                    } else {
                        // 使用第一个类别的颜色
                        seat.style.backgroundColor = getSeatTypeColor(0);
                    }
                });
            }
            
            // 生成主席台座位
            function generateStageSeats() {
                const stageRows = parseInt(document.getElementById('stageRows').value) || 1;
                const stageSeatsPerRow = parseInt(document.getElementById('stageSeatsPerRow').value) || 3;
                const alignment = document.getElementById('stageAlignment').value;
                
                stageContainer.innerHTML = '';
                
                // 主席台从下往上排列（序号1在最下面）
                for (let r = 0; r < stageRows; r++) {
                    const row = document.createElement('div');
                    row.className = 'stage-row';
                    
                    // 行号标签
                    const rowLabel = document.createElement('div');
                    rowLabel.className = 'stage-row-label';
                    // 主席台行号从下往上递增（视觉上最下面一排是第1排）
                    if(stageRows===1){
                        rowLabel.textContent = '';
                    }
                    else{
                        rowLabel.textContent = r+1;
                    }
                    row.appendChild(rowLabel);
                    
                    const rowContent = document.createElement('div');
                    rowContent.className = 'stage-row-content';
                    rowContent.dataset.row = r;
                    rowContent.dataset.type = 'stage';
                    
                    // 应用排列方式
                    if (alignment === 'center') {
                        rowContent.style.justifyContent = 'center';
                    } else if (alignment === 'right') {
                        rowContent.style.justifyContent = 'flex-end';
                    } else {
                        rowContent.style.justifyContent = 'flex-start';
                    }
                    
                    for (let s = 0; s < stageSeatsPerRow; s++) {
                        // 检查是否有保存的座位数据
                        const seatId = `stage-${r}-${s}`;
                        let seatData = null;
                        
                        if (window.seatDataStorage && window.seatDataStorage[seatId]) {
                            seatData = window.seatDataStorage[seatId];
                        } else {
                            const savedData = localStorage.getItem('seatingChartData');
                            if (savedData) {
                                const allData = JSON.parse(savedData);
                                seatData = allData[seatId];
                            }
                        }
                        
                        if (seatData && seatData.deleted) {
                            // 创建空位
                            const emptySpace = document.createElement('div');
                            emptySpace.className = 'empty-space';
                            emptySpace.dataset.id = seatId;
                            rowContent.appendChild(emptySpace);
                        } else {
                            const seat = document.createElement('div');
                            seat.className = 'seat';
                            seat.dataset.type = seatData ? seatData.type : '0';
                            seat.dataset.number = seatData ? seatData.number : `${stageRows - r}-${s+1}`;
                            seat.dataset.name = seatData ? seatData.name : `主席 ${stageRows - r}-${s+1}`;
                            seat.dataset.id = seatId;
                            seat.dataset.row = r;
                            seat.dataset.col = s;
                            seat.dataset.sortValue = s; // 初始化排序值
                            seat.innerHTML = `
                                <div class="seat-number">${seatData ? seatData.number : `${stageRows - r}-${s+1}`}</div>
                                <div class="seat-name">${seatData ? seatData.name : `主席 ${stageRows - r}-${s+1}`}</div>
                            `;
                            seat.style.backgroundColor = getSeatTypeColor(seatData ? seatData.type : 0);
                            seat.addEventListener('click', () => openEditModal(seat));
                            seat.addEventListener('mousedown', startDrag);
                            seat.addEventListener('mouseup', endDrag);
                            
                            rowContent.appendChild(seat);
                        }
                    }
                    
                    row.appendChild(rowContent);
                    stageContainer.appendChild(row);
                }
            }
            
            // 生成观众席座位
            function generateAudienceSeats() {
                const rowsCount = parseInt(document.getElementById('rows').value) || 5;
                const seatsPerRow = parseInt(document.getElementById('seatsPerRow').value) || 6;
                const alignment = document.getElementById('rowAlignment').value;
                const horizontalAisles = parseAisleSetting(document.getElementById('horizontalAisles').value);
                const verticalAisles = parseAisleSetting(document.getElementById('verticalAisles').value);
                
                audienceContainer.innerHTML = '';
                
                // 添加自定义排列提示
                if (alignment === 'custom') {
                    const hint = document.createElement('div');
                    hint.className = 'custom-layout-hint';
                    hint.textContent = '自定义排列模式：可以拖动座椅到任意位置';
                    audienceContainer.appendChild(hint);
                }
                
                for (let r = 0; r < rowsCount; r++) {
                    // 添加横向过道
                    if (horizontalAisles.includes(r)) {
                        const aisle = document.createElement('div');
                        aisle.className = 'aisle horizontal-aisle';
                        aisle.textContent = '过道';
                        aisle.style.fontSize = document.getElementById('aisleFontSize').value + 'px';
                        audienceContainer.appendChild(aisle);
                    }
                    
                    const row = document.createElement('div');
                    row.className = 'row';
                    
                    const rowLabel = document.createElement('div');
                    rowLabel.className = 'row-label';
                    rowLabel.textContent = r + 1;
                    row.appendChild(rowLabel);
                    
                    const rowContent = document.createElement('div');
                    rowContent.className = 'row-content';
                    rowContent.dataset.row = r;
                    
                    // 应用排列方式
                    if (alignment === 'custom') {
                        rowContent.classList.add('custom-layout');
                        // 加载自定义排列数据
                        applyCustomLayout(rowContent, r);
                    } else {
                        if (alignment === 'center') {
                            rowContent.style.justifyContent = 'center';
                        } else if (alignment === 'right') {
                            rowContent.style.justifyContent = 'flex-end';
                        } else {
                            rowContent.style.justifyContent = 'flex-start';
                        }
                    }
                    
                    for (let s = 0; s < seatsPerRow; s++) {
                        // 添加纵向过道
                        if (verticalAisles.includes(s)) {
                            const aisle = document.createElement('div');
                            aisle.className = 'aisle vertical-aisle';
                            aisle.textContent = '过道';
                            aisle.style.fontSize = document.getElementById('aisleFontSize').value + 'px';
                            rowContent.appendChild(aisle);
                        }
                        
                        // 检查是否有保存的座位数据
                        const seatId = `audience-${r}-${s}`;
                        let seatData = null;
                        
                        if (window.seatDataStorage && window.seatDataStorage[seatId]) {
                            seatData = window.seatDataStorage[seatId];
                        } else {
                            const savedData = localStorage.getItem('seatingChartData');
                            if (savedData) {
                                const allData = JSON.parse(savedData);
                                seatData = allData[seatId];
                            }
                        }
                        
                        if (seatData && seatData.deleted) {
                            // 创建空位
                            const emptySpace = document.createElement('div');
                            emptySpace.className = 'empty-space';
                            emptySpace.dataset.id = seatId;
                            rowContent.appendChild(emptySpace);
                        } else {
                            const seat = document.createElement('div');
                            seat.className = 'seat';
                            seat.dataset.type = seatData ? seatData.type : '0';
                            seat.dataset.number = seatData ? seatData.number : `${r+1}-${s+1}`;
                            seat.dataset.name = seatData ? seatData.name : `代表 ${r+1}-${s+1}`;
                            seat.dataset.id = seatId;
                            seat.dataset.row = r;
                            seat.dataset.col = s;
                            seat.dataset.sortValue = s; // 初始化排序值
                            seat.innerHTML = `
                                <div class="seat-number">${seatData ? seatData.number : `${r+1}-${s+1}`}</div>
                                <div class="seat-name">${seatData ? seatData.name : `代表 ${r+1}-${s+1}`}</div>
                            `;
                            seat.style.backgroundColor = getSeatTypeColor(seatData ? seatData.type : 0);
                            seat.addEventListener('click', () => openEditModal(seat));
                            seat.addEventListener('mousedown', startDrag);
                            seat.addEventListener('mouseup', endDrag);
                            
                            // 在自定义模式下，允许自由拖动位置
                            if (alignment === 'custom') {
                                makeSeatDraggable(seat);
                            }
                            
                            rowContent.appendChild(seat);
                        }
                    }
                    
                    row.appendChild(rowContent);
                    audienceContainer.appendChild(row);
                }
                
                // 如果数据已导入，不再重新生成
                if (isDataImported) {
                    isDataImported = false;
                }
            }
            
            // 使座椅可拖动（自定义排列模式）
            function makeSeatDraggable(seat) {
                seat.draggable = true;
                
                seat.addEventListener('dragstart', function(e) {
                    this.classList.add('dragging');
                    e.dataTransfer.setData('text/plain', this.dataset.id);
                });
                
                seat.addEventListener('dragend', function() {
                    this.classList.remove('dragging');
                    saveCustomLayout();
                    
                    // 新增：保存状态到历史记录
                    saveStateToHistory();
                });
                
                seat.addEventListener('dragover', function(e) {
                    e.preventDefault(); // 允许放置
                });
                
                seat.addEventListener('drop', function(e) {
                    e.preventDefault();
                    const draggedId = e.dataTransfer.getData('text/plain');
                    const draggedSeat = document.querySelector(`[data-id="${draggedId}"]`);
                    
                    if (draggedSeat && draggedSeat !== this) {
                        // 交换位置
                        const thisParent = this.parentNode;
                        const draggedParent = draggedSeat.parentNode;
                        
                        // 交换DOM位置
                        const thisNext = this.nextSibling;
                        const draggedNext = draggedSeat.nextSibling;
                        
                        thisParent.insertBefore(draggedSeat, thisNext);
                        draggedParent.insertBefore(this, draggedNext);
                        
                        // 保存自定义布局
                        saveCustomLayout();
                        
                        // 新增：保存状态到历史记录
                        saveStateToHistory();
                    }
                });
            }
            
            // 解析过道设置
            function parseAisleSetting(value) {
                if (!value) return [];
                return value.split(',').map(num => parseInt(num.trim()) - 1).filter(num => !isNaN(num));
            }
            
            // 更新过道颜色
            function updateAisleColor() {
                const color = document.getElementById('aisleColor').value;
                document.documentElement.style.setProperty('--aisle-color', color);
                
                // 更新所有过道颜色
                document.querySelectorAll('.aisle').forEach(aisle => {
                    aisle.style.backgroundColor = color;
                });
            }
            
            // 更新间距设置
            function updateGaps() {
                const stageRowGap = document.getElementById('stageRowGap').value;
                const audienceRowGap = document.getElementById('audienceRowGap').value;
                const stageAudienceGap = document.getElementById('stageAudienceGap').value;
                
                document.documentElement.style.setProperty('--stage-row-gap', stageRowGap + 'px');
                document.documentElement.style.setProperty('--audience-row-gap', audienceRowGap + 'px');
                document.documentElement.style.setProperty('--stage-audience-gap', stageAudienceGap + 'px');
                
                // 应用间距
                stageContainer.style.gap = stageRowGap + 'px';
                stageContainer.style.marginBottom = stageAudienceGap + 'px';
                audienceContainer.style.gap = audienceRowGap + 'px';
            }
            
            // 获取座位类型颜色
            function getSeatTypeColor(typeIndex) {
                const seatTypes = document.querySelectorAll('.seat-type');
                if (seatTypes[typeIndex]) {
                    return seatTypes[typeIndex].querySelector('input[type="color"]').value;
                }
                return '#3498db'; // 默认颜色
            }
            
            // 更新图例
            function updateLegend() {
                const showTypes = document.getElementById('showSeatTypes').checked;
                if (!showTypes) {
                    legendContainer.innerHTML = '';
                    return;
                }
                
                const seatTypes = document.querySelectorAll('.seat-type');
                legendContainer.innerHTML = '';
                
                seatTypes.forEach((type, index) => {
                    const colorInput = type.querySelector('input[type="color"]');
                    const textInput = type.querySelector('input[type="text"]');
                    
                    const legendItem = document.createElement('div');
                    legendItem.className = 'legend-item';
                    
                    const colorBox = document.createElement('span');
                    colorBox.className = 'color-preview';
                    colorBox.style.backgroundColor = colorInput.value;
                    
                    const label = document.createElement('span');
                    label.textContent = textInput.value || `类别 ${index+1}`;
                    
                    legendItem.appendChild(colorBox);
                    legendItem.appendChild(label);
                    legendContainer.appendChild(legendItem);
                });
            }
            
            // 应用所有设置
            function applySettings() {
                // 保存当前座位数据（包括已删除的座位）
                const currentData = getAllSeatData();
                
                generateStageSeats();
                generateAudienceSeats();
                updateLegend();
                updateConferenceTitle();
                updateSeatDisplay();
                updateSeatFontSize();
                updateSeatSize();
                updateStageSeatSize();
                updateGaps();
                updateAisleColor();
                toggleCustomLayoutHint();
                updateSeatTypeVisibility();
                
                // 恢复座位数据（包括已删除的座位）
                if (Object.keys(currentData).length > 0) {
                    applySeatData(currentData);
                } else {
                    loadSeatData();
                }
                
                // 如果是自定义排列模式，恢复自定义位置
                const alignment = document.getElementById('rowAlignment').value;
                if (alignment === 'custom') {
                    const rows = audienceContainer.querySelectorAll('.row-content');
                    rows.forEach((rowContent, index) => {
                        applyCustomLayout(rowContent, index);
                    });
                }
                
                // 新增：保存状态到历史记录
                saveStateToHistory();
                
                alert('设置已应用成功！');
            }
            
            // 获取所有座位数据（包括已删除的座位）
            function getAllSeatData() {
                const data = {};
                
                // 获取主席台座位数据
                const stageSeats = stageContainer.querySelectorAll('.seat, .empty-space');
                stageSeats.forEach(seat => {
                    if (seat.classList.contains('empty-space')) {
                        data[seat.dataset.id] = { deleted: true };
                    } else {
                        data[seat.dataset.id] = {
                            number: seat.dataset.number,
                            name: seat.dataset.name,
                            type: seat.dataset.type
                        };
                    }
                });
                
                // 获取观众席座位数据
                const audienceSeats = audienceContainer.querySelectorAll('.seat, .empty-space');
                audienceSeats.forEach(seat => {
                    if (seat.classList.contains('empty-space')) {
                        data[seat.dataset.id] = { deleted: true };
                    } else {
                        data[seat.dataset.id] = {
                            number: seat.dataset.number,
                            name: seat.dataset.name,
                            type: seat.dataset.type
                        };
                    }
                });
                
                return data;
            }
            
            // 应用座位数据
			function applySeatData(data) {
				for (const id in data) {
					// 处理已删除的座位
					if (data[id].deleted) {
						const existingSeat = document.querySelector(`[data-id="${id}"]`);
						if (existingSeat && existingSeat.classList.contains('seat')) {
							// 替换为空白区域
							const emptySpace = document.createElement('div');
							emptySpace.className = 'empty-space';
							emptySpace.dataset.id = id;
							
							// 设置空位尺寸
							if (id.startsWith('stage-')) {
								const width = document.getElementById('stageSeatWidth').value;
								const height = document.getElementById('stageSeatHeight').value;
								emptySpace.style.width = width + 'px';
								emptySpace.style.height = height + 'px';
							} else {
								const width = document.getElementById('seatWidth').value;
								const height = document.getElementById('seatHeight').value;
								emptySpace.style.width = width + 'px';
								emptySpace.style.height = height + 'px';
							}
							
							existingSeat.parentNode.replaceChild(emptySpace, existingSeat);
						}
						continue;
					}
					
					// 处理正常座位
					const seat = document.querySelector(`[data-id="${id}"]`);
					if (seat) {
						// 如果是空白区域，需要先创建座位
						if (seat.classList.contains('empty-space')) {
							const newSeat = document.createElement('div');
							newSeat.className = 'seat';
							newSeat.dataset.id = id;
							
							// 解析行列信息
							const idParts = id.split('-');
							const area = idParts[0];
							const row = parseInt(idParts[1]);
							const col = parseInt(idParts[2]);
							
							newSeat.dataset.row = row;
							newSeat.dataset.col = col;
							
							// 设置座位内容
							newSeat.innerHTML = `
								<div class="seat-number">${data[id].number}</div>
								<div class="seat-name">${data[id].name}</div>
							`;
							
							// 设置事件监听
							newSeat.addEventListener('click', () => openEditModal(newSeat));
							newSeat.addEventListener('mousedown', startDrag);
							newSeat.addEventListener('mouseup', endDrag);
							
							// 如果是自定义布局模式，使座位可拖动
							const alignment = document.getElementById('rowAlignment').value;
							if (alignment === 'custom') {
								makeSeatDraggable(newSeat);
							}
							
							// 替换空白区域
							seat.parentNode.replaceChild(newSeat, seat);
							
							// 更新座位数据
							newSeat.dataset.number = data[id].number;
							newSeat.dataset.name = data[id].name;
							newSeat.dataset.type = data[id].type;
						} else {
							// 更新现有座位数据
							seat.dataset.number = data[id].number;
							seat.dataset.name = data[id].name;
							seat.dataset.type = data[id].type;
							
							const numberEl = seat.querySelector('.seat-number');
							const nameEl = seat.querySelector('.seat-name');
							
							if (numberEl) numberEl.textContent = data[id].number;
							if (nameEl) nameEl.textContent = data[id].name;
						}
						
						// 根据是否显示类别设置颜色
						const showTypes = document.getElementById('showSeatTypes').checked;
						if (showTypes) {
							seat.style.backgroundColor = getSeatTypeColor(data[id].type);
						} else {
							seat.style.backgroundColor = getSeatTypeColor(0);
						}
					}
				}
				
				// 更新显示
				updateSeatDisplay();
				
				// 保存数据
				saveSeatData();
			}
            
            // 应用自定义布局
            function applyCustomLayout(rowContent, rowIndex) {
                const customLayoutData = JSON.parse(localStorage.getItem('customLayoutData') || '{}');
                const rowData = customLayoutData[rowIndex] || {};
                
                // 应用自定义位置
                for (const seatId in rowData) {
                    const seat = rowContent.querySelector(`[data-id="${seatId}"]`);
                    if (seat && rowData[seatId]) {
                        seat.style.position = 'absolute';
                        seat.style.left = `${rowData[seatId].x}px`;
                        seat.style.top = `${rowData[seatId].y}px`;
                        seat.style.zIndex = '10';
                    }
                }
            }
            
            // 保存自定义布局
            function saveCustomLayout() {
                const customLayoutData = {};
                const rows = audienceContainer.querySelectorAll('.row-content');
                
                rows.forEach(rowContent => {
                    const rowIndex = rowContent.dataset.row;
                    customLayoutData[rowIndex] = {};
                    
                    const seats = rowContent.querySelectorAll('.seat');
                    seats.forEach(seat => {
                        // 只保存绝对定位的座位
                        if (seat.style.position === 'absolute') {
                            customLayoutData[rowIndex][seat.dataset.id] = {
                                x: parseInt(seat.style.left) || 0,
                                y: parseInt(seat.style.top) || 0
                            };
                        }
                    });
                });
                
                localStorage.setItem('customLayoutData', JSON.stringify(customLayoutData));
            }
            
            // 更新会议标题
            function updateConferenceTitle() {
                const title = document.getElementById('conferenceTitle').value;
                const fontSize = document.getElementById('titleFontSize').value;
                conferenceTitleDisplay.textContent = title;
                conferenceTitleDisplay.style.fontSize = `${fontSize}px`;
            }
            
            // 更新观众席座位尺寸
            function updateSeatSize() {
                const width = document.getElementById('seatWidth').value;
                const height = document.getElementById('seatHeight').value;
                document.documentElement.style.setProperty('--seat-width', width + 'px');
                document.documentElement.style.setProperty('--seat-height', height + 'px');
                
                // 更新所有行标签高度
                document.querySelectorAll('.row-label').forEach(label => {
                    label.style.height = height + 'px';
                    label.style.lineHeight = height + 'px';
                });
                
                // 更新纵向过道高度
                document.querySelectorAll('.vertical-aisle').forEach(aisle => {
                    aisle.style.height = height + 'px';
                });
                
                // 更新空位尺寸
                document.querySelectorAll('.empty-space').forEach(space => {
                    space.style.width = width + 'px';
                    space.style.height = height + 'px';
                });
            }
            
            // 更新主席台座位尺寸
            function updateStageSeatSize() {
                const width = document.getElementById('stageSeatWidth').value;
                const height = document.getElementById('stageSeatHeight').value;
                
                // 更新主席台座位
                const stageSeats = stageContainer.querySelectorAll('.seat');
                stageSeats.forEach(seat => {
                    seat.style.width = width + 'px';
                    seat.style.minHeight = height + 'px';
                });
                
                // 更新主席台行标签高度
                document.querySelectorAll('.stage-row-label').forEach(label => {
                    label.style.height = height + 'px';
                    label.style.lineHeight = height + 'px';
                });
                
                // 更新主席台空位尺寸
                const stageEmptySpaces = stageContainer.querySelectorAll('.empty-space');
                stageEmptySpaces.forEach(space => {
                    space.style.width = width + 'px';
                    space.style.height = height + 'px';
                });
            }
            
            // 更新座位显示方式
            function updateSeatDisplay() {
                const displayOption = document.getElementById('seatDisplay').value;
                const seats = document.querySelectorAll('.seat');
                
                seats.forEach(seat => {
                    const number = seat.querySelector('.seat-number');
                    const name = seat.querySelector('.seat-name');
                    
                    number.classList.remove('hidden');
                    name.classList.remove('hidden');
                    
                    if (displayOption === 'number') {
                        name.classList.add('hidden');
                    } else if (displayOption === 'name') {
                        number.classList.add('hidden');
                    } else if (displayOption === 'none') {
                        number.classList.add('hidden');
                        name.classList.add('hidden');
                    }
                });
            }
            
            // 更新座位字体大小
            function updateSeatFontSize() {
                const fontSize = document.getElementById('seatFontSize').value;
                const seats = document.querySelectorAll('.seat');
                
                seats.forEach(seat => {
                    seat.style.fontSize = `${fontSize}px`;
                });
            }
            
            // 添加座位类别
            function addSeatType() {
                const seatTypesContainer = document.getElementById('seatTypes');
                const newType = document.createElement('div');
                newType.className = 'seat-type';
                newType.innerHTML = `
                    <input type="color" value="#${Math.floor(Math.random()*16777215).toString(16)}">
                    <input type="text" placeholder="新类别">
                `;
                seatTypesContainer.appendChild(newType);
                updateLegend();
                
                // 新增：保存状态到历史记录
                saveStateToHistory();
            }
            
            // 打开编辑模态框
            function openEditModal(seat) {
                if (dragging) return;
                
                currentSeat = seat;
                document.getElementById('editSeatNumber').value = seat.dataset.number;
                document.getElementById('editSeatName').value = seat.dataset.name;
                document.getElementById('editSeatType').value = seat.dataset.type;
                
                editSeatModal.style.display = 'flex';
            }
            
            // 关闭编辑模态框
            function closeEditModal() {
                editSeatModal.style.display = 'none';
            }
            
            // 保存座位编辑
            function saveSeatEdit() {
                if (!currentSeat) return;
                
                const number = document.getElementById('editSeatNumber').value;
                const name = document.getElementById('editSeatName').value;
                const type = document.getElementById('editSeatType').value;
                
                currentSeat.dataset.number = number;
                currentSeat.dataset.name = name;
                currentSeat.dataset.type = type;
                
                // 更新座位颜色
                const showTypes = document.getElementById('showSeatTypes').checked;
                if (showTypes) {
                    currentSeat.style.backgroundColor = getSeatTypeColor(type);
                } else {
                    currentSeat.style.backgroundColor = getSeatTypeColor(0);
                }
                
                // 更新显示内容
                const displayOption = document.getElementById('seatDisplay').value;
                const numberEl = currentSeat.querySelector('.seat-number');
                const nameEl = currentSeat.querySelector('.seat-name');
                
                numberEl.textContent = number;
                nameEl.textContent = name;
                
                numberEl.classList.remove('hidden');
                nameEl.classList.remove('hidden');
                
                if (displayOption === 'number') {
                    nameEl.classList.add('hidden');
                } else if (displayOption === 'name') {
                    numberEl.classList.add('hidden');
                } else if (displayOption === 'none') {
                    numberEl.classList.add('hidden');
                    nameEl.classList.add('hidden');
                }
                
                // 保存座位数据
                saveSeatData();
                
                // 新增：保存状态到历史记录
                saveStateToHistory();
                
                closeEditModal();
            }
            
            // 删除座位
			function deleteSeat() {
				if (!currentSeat) return;
				
				if (confirm('确定要删除这个座位吗？')) {
					// 保存当前状态到历史记录（删除前）
					saveStateToHistory();
					
					const seatId = currentSeat.dataset.id;
					const row = currentSeat.dataset.row;
					const isStage = currentSeat.closest('.stage-container');
					
					// 创建空位元素替换座位
					const emptySpace = document.createElement('div');
					emptySpace.className = 'empty-space';
					emptySpace.dataset.id = seatId;
					
					// 设置空位尺寸
					if (isStage) {
						const width = document.getElementById('stageSeatWidth').value;
						const height = document.getElementById('stageSeatHeight').value;
						emptySpace.style.width = width + 'px';
						emptySpace.style.height = height + 'px';
					} else {
						const width = document.getElementById('seatWidth').value;
						const height = document.getElementById('seatHeight').value;
						emptySpace.style.width = width + 'px';
						emptySpace.style.height = height + 'px';
					}
					
					currentSeat.parentNode.replaceChild(emptySpace, currentSeat);
					
					// 标记该座位为已删除
					const savedData = localStorage.getItem('seatingChartData');
					if (savedData) {
						const allData = JSON.parse(savedData);
						allData[seatId] = { deleted: true };
						localStorage.setItem('seatingChartData', JSON.stringify(allData));
					}
					
					// 重新编号该行的其他座位
					if (!isStage) {
						renumberRow(row);
					}
					
					// 保存状态到历史记录（删除后）
					saveStateToHistory();
					
					closeEditModal();
				}
			}
            
            // 重新编号行中的座位
            function renumberRow(rowIndex) {
                const row = document.querySelector(`.row-content [data-row="${rowIndex}"]`)?.closest('.row');
                if (!row) return;
                
                const seats = row.querySelectorAll('.seat');
                let seatCount = 1;
                
                seats.forEach(seat => {
                    const newNumber = `${parseInt(rowIndex) + 1}-${seatCount}`;
                    seat.dataset.number = newNumber;
                    
                    const numberEl = seat.querySelector('.seat-number');
                    if (numberEl) {
                        numberEl.textContent = newNumber;
                    }
                    
                    seatCount++;
                });
                
                // 保存数据
                saveSeatData();
            }
            
            // 开始拖拽
            function startDrag(e) {
                dragging = true;
                dragSource = this;
                this.classList.add('selected');
                e.preventDefault();
            }
            
            // 结束拖拽
            function endDrag(e) {
                if (!dragging) return;
                
                this.classList.remove('selected');
                
                if (dragSource && dragSource !== this && !dragSource.classList.contains('empty') && !this.classList.contains('empty')) {
                    // 仅交换座牌名称
                    const tempName = dragSource.dataset.name;
                    
                    dragSource.dataset.name = this.dataset.name;
                    this.dataset.name = tempName;
                    
                    // 更新显示
                    const sourceName = dragSource.querySelector('.seat-name');
                    const targetName = this.querySelector('.seat-name');
                    
                    sourceName.textContent = dragSource.dataset.name;
                    targetName.textContent = this.dataset.name;
                    
                    // 保存座位数据
                    saveSeatData();
                    
                    // 新增：保存状态到历史记录
                    saveStateToHistory();
                }
                
                dragging = false;
                dragSource = null;
            }
            
            // 保存座位数据
            function saveSeatData() {
                seatData = {};
                
                // 保存主席台座位
                const stageSeats = stageContainer.querySelectorAll('.seat, .empty-space');
                stageSeats.forEach(seat => {
                    if (seat.classList.contains('empty-space')) {
                        seatData[seat.dataset.id] = { deleted: true };
                    } else {
                        seatData[seat.dataset.id] = {
                            number: seat.dataset.number,
                            name: seat.dataset.name,
                            type: seat.dataset.type
                        };
                    }
                });
                
                // 保存观众席座位
                const audienceSeats = audienceContainer.querySelectorAll('.seat, .empty-space');
                audienceSeats.forEach(seat => {
                    if (seat.classList.contains('empty-space')) {
                        seatData[seat.dataset.id] = { deleted: true };
                    } else {
                        seatData[seat.dataset.id] = {
                            number: seat.dataset.number,
                            name: seat.dataset.name,
                            type: seat.dataset.type
                        };
                    }
                });
                
                // 保存到localStorage
                localStorage.setItem('seatingChartData', JSON.stringify(seatData));
            }
            
            // 加载座位数据
            function loadSeatData() {
                const savedData = localStorage.getItem('seatingChartData');
                if (!savedData) return;
                
                seatData = JSON.parse(savedData);
                
                // 应用保存的数据
                for (const id in seatData) {
                    const seat = document.querySelector(`[data-id="${id}"]`);
                    if (seat) {
                        if (seatData[id].deleted) {
                            // 如果数据标记为已删除，则替换为空位
                            const emptySpace = document.createElement('div');
                            emptySpace.className = 'empty-space';
                            emptySpace.dataset.id = id;
                            
                            // 设置空位尺寸
                            if (id.startsWith('stage-')) {
                                const width = document.getElementById('stageSeatWidth').value;
                                const height = document.getElementById('stageSeatHeight').value;
                                emptySpace.style.width = width + 'px';
                                emptySpace.style.height = height + 'px';
                            } else {
                                const width = document.getElementById('seatWidth').value;
                                const height = document.getElementById('seatHeight').value;
                                emptySpace.style.width = width + 'px';
                                emptySpace.style.height = height + 'px';
                            }
                            
                            seat.parentNode.replaceChild(emptySpace, seat);
                        } else {
                            seat.dataset.number = seatData[id].number;
                            seat.dataset.name = seatData[id].name;
                            seat.dataset.type = seatData[id].type;
                            
                            const numberEl = seat.querySelector('.seat-number');
                            const nameEl = seat.querySelector('.seat-name');
                            
                            if (numberEl) numberEl.textContent = seatData[id].number;
                            if (nameEl) nameEl.textContent = seatData[id].name;
                            
                            // 根据是否显示类别设置颜色
                            const showTypes = document.getElementById('showSeatTypes').checked;
                            if (showTypes) {
                                seat.style.backgroundColor = getSeatTypeColor(seatData[id].type);
                            } else {
                                seat.style.backgroundColor = getSeatTypeColor(0);
                            }
                        }
                    }
                }
                
                // 更新显示
                updateSeatDisplay();
            }
            
            // 打印座次图
            function printSeatingChart() {
                window.print();
            }
            
            // 重置所有数据
            function resetAllData() {
                if (confirm('确定要重置所有数据吗？这将清除所有当前设置和座位信息。')) {
                    // 重置表单设置
                    document.getElementById('conferenceTitle').value = '会议活动名称';
                    document.getElementById('titleFontSize').value = '24';
                    document.getElementById('stageRows').value = '1';
                    document.getElementById('stageSeatsPerRow').value = '3';
                    document.getElementById('stageSeatWidth').value = '100';
                    document.getElementById('stageSeatHeight').value = '70';
                    document.getElementById('stageAlignment').value = 'center';
                    document.getElementById('rows').value = '5';
                    document.getElementById('seatsPerRow').value = '6';
                    document.getElementById('seatWidth').value = '80';
                    document.getElementById('seatHeight').value = '60';
                    document.getElementById('rowAlignment').value = 'center';
                    document.getElementById('stageRowGap').value = '15';
                    document.getElementById('audienceRowGap').value = '15';
                    document.getElementById('stageAudienceGap').value = '40';
                    document.getElementById('horizontalAisles').value = '';
                    document.getElementById('verticalAisles').value = '';
                    document.getElementById('aisleFontSize').value = '14';
                    document.getElementById('aisleColor').value = '#f0f0f0';
                    document.getElementById('seatDisplay').value = 'both';
                    document.getElementById('seatFontSize').value = '12';
                    document.getElementById('showSeatTypes').checked = true;
                    document.getElementById('sortingMethod').value = 'leftToRight';
                    
                    // 重置座位类型
                    const seatTypesContainer = document.getElementById('seatTypes');
                    seatTypesContainer.innerHTML = `
                        <div class="seat-type">
                            <input type="color" value="#3498db">
                            <input type="text" value="普通代表" placeholder="类别名称">
                        </div>
                        <div class="seat-type">
                            <input type="color" value="#e74c3c">
                            <input type="text" value="VIP代表" placeholder="类别名称">
                        </div>
                        <div class="seat-type">
                            <input type="color" value="#2ecc71">
                            <input type="text" value="工作人员" placeholder="类别名称">
                        </div>
                    `;
                    
                    // 清除所有保存的数据
                    localStorage.removeItem('seatingChartData');
                    localStorage.removeItem('customLayoutData');
                    
                    // 清除临时存储数据
                    if (window.seatDataStorage) {
                        delete window.seatDataStorage;
                    }
                    
                    // 重置导入标志
                    isDataImported = false;
                    
                    // 清除文件输入
                    csvFileInput.value = '';
                    
                    // 重新生成布局
                    generateStageSeats();
                    generateAudienceSeats();
                    updateLegend();
                    updateConferenceTitle();
                    updateSeatDisplay();
                    updateSeatFontSize();
                    updateSeatSize();
                    updateStageSeatSize();
                    updateGaps();
                    updateAisleColor();
                    toggleCustomLayoutHint();
                    updateSeatTypeVisibility();
                    
                    // 新增：保存状态到历史记录
                    saveStateToHistory();
                    
                    alert('所有数据已重置成功！');
                }
            }
            
            // 导入CSV
            function importCSV(event) {
                const file = event.target.files[0];
                if (!file) return;
                
                const reader = new FileReader();
                reader.onload = function(e) {
                    const csvData = e.target.result;
                    parseCSVData(csvData);
                    
                    // 新增：保存状态到历史记录
                    saveStateToHistory();
                };
                reader.readAsText(file);
            }
            
            // 解析CSV数据
            function parseCSVData(csvData) {
                const rows = csvData.split('\n');
                const importedData = {};
                
                // 分析导入数据中的行列信息
                let maxStageRow = -1;
                let maxStageCol = -1;
                let maxAudienceRow = -1;
                let maxAudienceCol = -1;
                let maxCategory = -1;
                
                // 存储所有有数据的座位位置，用于后续识别空座位
                const existingSeats = {
                    stage: {},
                    audience: {}
                };
                
                // 跳过标题行，从第二行开始
                for (let i = 1; i < rows.length; i++) {
                    const cells = rows[i].split(',');
                    if (cells.length < 6) continue;
                    
                    const position = parseInt(cells[0].trim());
                    const row = parseInt(cells[1].trim());
                    const col = parseInt(cells[2].trim());
                    const number = cells[3].trim();
                    const name = cells[4].trim();
                    const category = parseInt(cells[5].trim());
                    
                    // 更新最大类别值
                    if (category > maxCategory) maxCategory = category;
                    
                    // 生成座位ID
                    const seatId = `${position === 0 ? 'stage' : 'audience'}-${row-1}-${col-1}`;
                    
                    // 存储数据
                    importedData[seatId] = {
                        number: number,
                        name: name,
                        type: category.toString()
                    };
                    
                    // 记录存在的座位位置
                    const area = position === 0 ? 'stage' : 'audience';
                    if (!existingSeats[area][row]) {
                        existingSeats[area][row] = new Set();
                    }
                    existingSeats[area][row].add(col);
                    
                    // 更新最大行列信息
                    if (position === 0) {
                        if (row > maxStageRow) maxStageRow = row;
                        if (col > maxStageCol) maxStageCol = col;
                    } else {
                        if (row > maxAudienceRow) maxAudienceRow = row;
                        if (col > maxAudienceCol) maxAudienceCol = col;
                    }
                }
                
                // 处理空座位 - 为主席台和观众席中缺失的座位添加空座位标记
                // 主席台空座位处理
                for (let row = 1; row <= maxStageRow; row++) {
                    for (let col = 1; col <= maxStageCol; col++) {
                        const seatId = `stage-${row-1}-${col-1}`;
                        
                        // 如果这个座位在导入数据中不存在，标记为空座位
                        if (!importedData[seatId] && 
                            (!existingSeats.stage[row] || !existingSeats.stage[row].has(col))) {
                            importedData[seatId] = { deleted: true };
                        }
                    }
                }
                
                // 观众席空座位处理
                for (let row = 1; row <= maxAudienceRow; row++) {
                    for (let col = 1; col <= maxAudienceCol; col++) {
                        const seatId = `audience-${row-1}-${col-1}`;
                        
                        // 如果这个座位在导入数据中不存在，标记为空座位
                        if (!importedData[seatId] && 
                            (!existingSeats.audience[row] || !existingSeats.audience[row].has(col))) {
                            importedData[seatId] = { deleted: true };
                        }
                    }
                }
                
                // 更新表单设置
                if (maxStageRow > 0) {
                    document.getElementById('stageRows').value = maxStageRow;
                    document.getElementById('stageSeatsPerRow').value = maxStageCol;
                }
                
                if (maxAudienceRow > 0) {
                    document.getElementById('rows').value = maxAudienceRow;
                    document.getElementById('seatsPerRow').value = maxAudienceCol;
                }
                
                // 如果导入的类别数量超过当前类别数量，添加新类别
                const seatTypesContainer = document.getElementById('seatTypes');
                const currentCategoryCount = seatTypesContainer.querySelectorAll('.seat-type').length;
                
                if (maxCategory >= currentCategoryCount) {
                    for (let i = currentCategoryCount; i <= maxCategory; i++) {
                        const newType = document.createElement('div');
                        newType.className = 'seat-type';
                        newType.innerHTML = `
                            <input type="color" value="#${Math.floor(Math.random()*16777215).toString(16)}">
                            <input type="text" value="类别 ${i+1}" placeholder="类别名称">
                        `;
                        seatTypesContainer.appendChild(newType);
                    }
                    updateLegend();
                }
                
                // 临时存储导入的数据（包括空座位）
                window.seatDataStorage = importedData;
                isDataImported = true;
                
                // 重新生成座位以应用导入的数据
                generateStageSeats();
                generateAudienceSeats();
                
                // 保存数据
                saveSeatData();
                
                alert('CSV数据导入成功！');
                
                // 清空文件输入
                csvFileInput.value = '';
            }
            
            // 导出CSV
            function exportCSV() {
                // 收集所有座位数据
                let csvContent = "位置,行号,列号,座椅编号,座牌名称,类别\n";
                
                // 主席台座位
                const stageSeats = stageContainer.querySelectorAll('.seat');
                stageSeats.forEach(seat => {
                    const idParts = seat.dataset.id.split('-');
                    const row = parseInt(idParts[1]) + 1;
                    const col = parseInt(idParts[2]) + 1;
                    
                    csvContent += `0,${row},${col},${seat.dataset.number},${seat.dataset.name},${seat.dataset.type}\n`;
                });
                
                // 观众席座位
                const audienceSeats = audienceContainer.querySelectorAll('.seat');
                audienceSeats.forEach(seat => {
                    const idParts = seat.dataset.id.split('-');
                    const row = parseInt(idParts[1]) + 1;
                    const col = parseInt(idParts[2]) + 1;
                    
                    csvContent += `1,${row},${col},${seat.dataset.number},${seat.dataset.name},${seat.dataset.type}\n`;
                });
                
                // 创建下载链接
                const blob = new Blob([csvDataToUTF8(csvContent)], { type: 'text/csv;charset=utf-8;' });
                const url = URL.createObjectURL(blob);
                const link = document.createElement('a');
                link.setAttribute('href', url);
                link.setAttribute('download', '座次图数据.csv');
                link.style.visibility = 'hidden';
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
            
            // 将CSV数据转换为UTF-8格式（解决中文乱码问题）
            function csvDataToUTF8(csvData) {
                const BOM = '\uFEFF';
                return BOM + csvData;
            }
            
            // 应用排序
            function applySorting() {
                const sortingMethod = document.getElementById('sortingMethod').value;
                
                // 对观众席进行排序
                const audienceRows = audienceContainer.querySelectorAll('.row-content');
                audienceRows.forEach(row => {
                    const seats = Array.from(row.querySelectorAll('.seat'));
                    const seatCount = seats.length;
                    
                    // 收集所有座位的原始名称
                    const originalNames = seats.map(seat => seat.dataset.name);
                    
                    // 计算每个座位的排序值
                    seats.forEach((seat, index) => {
                        const col = parseInt(seat.dataset.col);
                        let sortValue = col; // 默认从左向右
                        
                        if (sortingMethod === 'rightToLeft') {
                            // 从右向左排序
                            sortValue = seatCount - 1 - col;
                        } else if (sortingMethod === 'centerToSidesLeftFirst') {
                            // 中间向两侧排序（左为尊）
                            sortValue = calculateCenterToSidesSortValue(col, seatCount, true);
                        } else if (sortingMethod === 'centerToSidesRightFirst') {
                            // 中间向两侧排序（右为尊）
                            sortValue = calculateCenterToSidesSortValue(col, seatCount, false);
                        }
                        
                        seat.dataset.sortValue = sortValue;
                    });
                    
                    // 按排序值排序座位
                    seats.sort((a, b) => {
                        return parseInt(a.dataset.sortValue) - parseInt(b.dataset.sortValue);
                    });
                    
                    // 将排序后的名称重新分配给座位
                    seats.forEach((seat, index) => {
                        seat.dataset.name = originalNames[index];
                        const nameEl = seat.querySelector('.seat-name');
                        if (nameEl) {
                            nameEl.textContent = originalNames[index];
                        }
                    });
                });
                
                // 对主席台进行排序（与观众席相反）
                const stageRows = stageContainer.querySelectorAll('.stage-row-content');
                stageRows.forEach(row => {
                    const seats = Array.from(row.querySelectorAll('.seat'));
                    const seatCount = seats.length;
                    
                    // 收集所有座位的原始名称
                    const originalNames = seats.map(seat => seat.dataset.name);
                    
                    // 计算每个座位的排序值（与观众席相反）
                    seats.forEach((seat, index) => {
                        const col = parseInt(seat.dataset.col);
                        let sortValue = col; // 默认从右向左（与观众席相反）
                        
                        if (sortingMethod === 'rightToLeft') {
                            // 从左向右排序（与观众席相反）
                            sortValue = seatCount - 1 - col;
                        } else if (sortingMethod === 'centerToSidesLeftFirst') {
                            // 中间向两侧排序（右为尊，与观众席相反）
                            sortValue = calculateCenterToSidesSortValue(col, seatCount, false);
                        } else if (sortingMethod === 'centerToSidesRightFirst') {
                            // 中间向两侧排序（左为尊，与观众席相反）
                            sortValue = calculateCenterToSidesSortValue(col, seatCount, true);
                        }
                        
                        seat.dataset.sortValue = sortValue;
                    });
                    
                    // 按排序值排序座位
                    seats.sort((a, b) => {
                        return parseInt(a.dataset.sortValue) - parseInt(b.dataset.sortValue);
                    });
                    
                    // 将排序后的名称重新分配给座位
                    seats.forEach((seat, index) => {
                        seat.dataset.name = originalNames[index];
                        const nameEl = seat.querySelector('.seat-name');
                        if (nameEl) {
                            nameEl.textContent = originalNames[index];
                        }
                    });
                });
                
                // 保存数据
                saveSeatData();
                
                // 新增：保存状态到历史记录
                saveStateToHistory();
                
                alert('排序已应用成功！');
            }
            
            // 计算中间向两侧排序的排序值
            function calculateCenterToSidesSortValue(col, seatCount, leftFirst) {
                let sortValue = 0;
                
                if (seatCount % 2 === 1) {
                    // 奇数个座位
                    const center = Math.floor(seatCount / 2);
                    const distance = Math.abs(col - center);
                    
                    if (col === center) {
                        sortValue = 0; // 中间位置最重要
                    } else if (col < center) {
                        // 左侧座位
                        if (leftFirst) {
                            // 左为尊：左侧座位按距离中心从近到远，排序值递增
                            sortValue = (center - col) * 2 - 1;
                        } else {
                            // 右为尊：左侧座位排序值较大
                            sortValue = (center - col) * 2;
                        }
                    } else {
                        // 右侧座位
                        if (leftFirst) {
                            // 左为尊：右侧座位排序值较大
                            sortValue = (col - center) * 2;
                        } else {
                            // 右为尊：右侧座位按距离中心从近到远，排序值递增
                            sortValue = (col - center) * 2 - 1;
                        }
                    }
                } else {
                    // 偶数个座位
                    const centerRight = seatCount / 2;
                    const centerLeft = centerRight - 1;
                    
                    if (leftFirst) {
                        // 左为尊：选择最中间两个位置中偏右的那个位置作为1号
                        if (col === centerRight) {
                            sortValue = 0;
                        } else if (col === centerLeft) {
                            sortValue = 1;
                        } else if (col < centerLeft) {
                            // 左侧座位
                            sortValue = (centerLeft - col) * 2 + 2;
                        } else {
                            // 右侧座位
                            sortValue = (col - centerRight) * 2 + 1;
                        }
                    } else {
                        // 右为尊：选择最中间两个位置中偏左的那个位置作为1号
                        if (col === centerLeft) {
                            sortValue = 0;
                        } else if (col === centerRight) {
                            sortValue = 1;
                        } else if (col < centerLeft) {
                            // 左侧座位
                            sortValue = (centerLeft - col) * 2 + 1;
                        } else {
                            // 右侧座位
                            sortValue = (col - centerRight) * 2 + 2;
                        }
                    }
                }
                
                return sortValue;
            }
            
            // 添加文档级别的鼠标事件监听，用于处理拖拽
            document.addEventListener('mouseover', function(e) {
                if (dragging && e.target.classList.contains('seat') && e.target !== dragSource) {
                    e.target.classList.add('selected');
                }
            });
            
            document.addEventListener('mouseout', function(e) {
                if (e.target.classList.contains('seat')) {
                    e.target.classList.remove('selected');
                }
            });
        });
    </script>
</body>
</html>